package org.linlinjava.litemall.admin.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.Validate;
import org.linlinjava.litemall.admin.beans.dto.ShopProxyRefundDto;
import org.linlinjava.litemall.admin.beans.dto.ShopRefundDto;
import org.linlinjava.litemall.admin.beans.vo.RefundDetailVo;
import org.linlinjava.litemall.admin.beans.vo.RefundGoodsVo;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrderGoods;
import org.linlinjava.litemall.db.domain.LitemallOrderGoodsAccessory;
import org.linlinjava.litemall.db.domain.LitemallRefund;
import org.linlinjava.litemall.db.domain.LitemallRefundGoods;
import org.linlinjava.litemall.db.domain.LitemallRefundTax;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.RefundStatisticsVo;
import org.linlinjava.litemall.db.domain.ShopRefundListQuery;
import org.linlinjava.litemall.db.domain.ShopRefundListVo;
import org.linlinjava.litemall.db.domain.TaxStatisticsDetailVo;
import org.linlinjava.litemall.db.domain.TotalRefundStatisticsVo;
import org.linlinjava.litemall.db.domain.TotalShopRefundStatisticsVo;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsAccessoryService;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.LitemallRefundGoodsService;
import org.linlinjava.litemall.db.service.LitemallRefundService;
import org.linlinjava.litemall.db.service.LitemallRefundTaxService;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * 管理退款服务
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Service
public class AdminRefundService {

    /**
     * 退款服务
     */
    @Autowired
    private LitemallRefundService refundService;
    /**
     * 订单商品服务
     */
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    /**
     * 退还商品服务
     */
    @Autowired
    private LitemallRefundGoodsService refundGoodsService;
    /**
     * litemall订货配件服务
     */
    @Autowired
    private LitemallOrderGoodsAccessoryService litemallOrderGoodsAccessoryService;
    /**
     * 退还税收服务
     */
    @Autowired
    private LitemallRefundTaxService refundTaxService;
    /**
     * 店服务
     */
    @Autowired
    private LitemallShopService shopService;
    /**
     * 用户服务
     */
    @Autowired
    private LitemallUserService userService;

    /**
     * 统计数据
     * 退款按月统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param regionId  区域id
     * @param page      页面
     * @param limit     限制
     * @return {@link Object}
     */
    public Object statistics(String startTime, String endTime, Integer regionId, Integer page, Integer limit) {
    	List<RefundStatisticsVo> result = refundService.statistics(startTime, endTime, regionId, page, limit);
    	if(!CollectionUtils.isEmpty(result)) {
    		for (RefundStatisticsVo refundStatisticsVo : result) {
    			List<TaxStatisticsDetailVo> taxDetailLs = refundTaxService.statistics(startTime, endTime, refundStatisticsVo.getShopId());
    			refundStatisticsVo.setTaxDetailLs(taxDetailLs);
    		}
    	}
    	return ResponseUtil.okList(result);
    }

    /**
     * 总统计
     * 汇总统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param regionId  区域id
     * @return {@link Object}
     */
    public Object totalStatistics(String startTime, String endTime, Integer regionId) {
    	TotalRefundStatisticsVo totalStatisticsVo = refundService.totalStatistics(startTime, endTime, regionId);
    	List<TaxStatisticsDetailVo> taxDetailLs = refundTaxService.totalStatistics(startTime, endTime, regionId);
    	totalStatisticsVo.setTaxDetailLs(taxDetailLs);
    	return ResponseUtil.ok(totalStatisticsVo);
    }

    /**
     * 代理数据
     * 代理退款按月统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param regionId  区域id
     * @param page      页面
     * @param limit     限制
     * @return {@link Object}
     */
    public Object proxyStatistics(String startTime, String endTime, Integer regionId, Integer page, Integer limit) {
    	List<RefundStatisticsVo> result = refundService.proxyStatistics(startTime, endTime, regionId, page, limit);
    	if(!CollectionUtils.isEmpty(result)) {
    		for (RefundStatisticsVo refundStatisticsVo : result) {
    			List<TaxStatisticsDetailVo> taxDetailLs = refundTaxService.proxyStatistics(startTime, endTime, refundStatisticsVo.getShopId());
    			refundStatisticsVo.setTaxDetailLs(taxDetailLs);
    		}
    	}
    	return ResponseUtil.okList(result);
    }

    /**
     * 代理总统计
     * 代理退款汇总统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param regionId  区域id
     * @return {@link Object}
     */
    public Object proxyTotalStatistics(String startTime, String endTime, Integer regionId) {
    	TotalRefundStatisticsVo totalStatisticsVo = refundService.proxyTotalStatistics(startTime, endTime, regionId);
    	List<TaxStatisticsDetailVo> taxDetailLs = refundTaxService.proxyTotalStatistics(startTime, endTime, regionId);
    	totalStatisticsVo.setTaxDetailLs(taxDetailLs);
    	return ResponseUtil.ok(totalStatisticsVo);
    }

    /**
     * 商店退款名单
     * 门店退款查询列表
     *
     * @param shopRefundDto 商店退款dto
     * @param page          页面
     * @param limit         限制
     * @return {@link Object}
     */
    public Object shopRefundList(ShopRefundDto shopRefundDto, Integer page, Integer limit) {
    	ShopRefundListQuery query = new ShopRefundListQuery();
    	BeanUtils.copyProperties(shopRefundDto, query);
    	Integer orderShopId = shopRefundDto.getShopId();
    	query.setOrderShopId(orderShopId);
    	
    	IPage<ShopRefundListVo> result = refundService.shopRefundList(query, page, limit);
    	if(!CollectionUtils.isEmpty(result.getRecords())) {
			result.getRecords().forEach(refundListVo->{
				List<TaxStatisticsDetailVo> taxDetailLs = refundTaxService.queryByRefundId(refundListVo.getId());
				refundListVo.setTaxDetailLs(taxDetailLs);
			});
    	}
    	return ResponseUtil.okPage(result);
    }

    /**
     * 店总统计
     * 店铺退款汇总统计
     *
     * @param shopRefundDto 商店退款dto
     * @return {@link Object}
     */
    public Object totalShopStatistic(ShopRefundDto shopRefundDto) {
    	ShopRefundListQuery query = new ShopRefundListQuery();
    	BeanUtils.copyProperties(shopRefundDto, query);
    	Integer orderShopId = shopRefundDto.getShopId();
    	query.setOrderShopId(orderShopId);
    	
    	TotalShopRefundStatisticsVo totalShopRefundStatisticsVo = refundService.totalShopStatistic(query);
    	totalShopRefundStatisticsVo.setShopId(orderShopId);
    	totalShopRefundStatisticsVo.setShopName(getShopName(orderShopId));
    	
    	totalShopRefundStatisticsVo.setStartTime(shopRefundDto.getStartTime());
    	totalShopRefundStatisticsVo.setEndTime(shopRefundDto.getEndTime());
    	List<TaxStatisticsDetailVo> taxDetailLs = refundTaxService.totalShopStatistic(query);
    	totalShopRefundStatisticsVo.setTaxDetailLs(taxDetailLs);
    	return ResponseUtil.ok(totalShopRefundStatisticsVo);
    }

    /**
     * 店代理退款名单
     * 门店代理退款查询列表
     *
     * @param shopProxyRefundDto 店代理退款dto
     * @param page               页面
     * @param limit              限制
     * @return {@link Object}
     */
    public Object shopProxyRefundList(ShopProxyRefundDto shopProxyRefundDto, Integer page, Integer limit) {
    	ShopRefundListQuery query = new ShopRefundListQuery();
    	BeanUtils.copyProperties(shopProxyRefundDto, query);
    	Integer refundShopId = shopProxyRefundDto.getShopId();
    	query.setProxyRefundShopId(refundShopId);
    	
    	IPage<ShopRefundListVo> result = refundService.shopRefundList(query, page, limit);
    	if(!CollectionUtils.isEmpty(result.getRecords())) {
			result.getRecords().forEach(refundListVo->{
				List<TaxStatisticsDetailVo> taxDetailLs = refundTaxService.queryByRefundId(refundListVo.getId());
				refundListVo.setTaxDetailLs(taxDetailLs);
			});
    	}
    	return ResponseUtil.okPage(result);
    }

    /**
     * 店代理总统计
     * 店铺退款汇总统计
     *
     * @param shopProxyRefundDto 店代理退款dto
     * @return {@link Object}
     */
    public Object totalShopProxyStatistic(ShopProxyRefundDto shopProxyRefundDto) {
    	ShopRefundListQuery query = new ShopRefundListQuery();
    	BeanUtils.copyProperties(shopProxyRefundDto, query);
    	Integer refundShopId = shopProxyRefundDto.getShopId();
    	query.setProxyRefundShopId(refundShopId);
    	
    	TotalShopRefundStatisticsVo totalShopRefundStatisticsVo = refundService.totalShopStatistic(query);

    	totalShopRefundStatisticsVo.setShopId(refundShopId);
    	totalShopRefundStatisticsVo.setShopName(getShopName(refundShopId));
    	
    	totalShopRefundStatisticsVo.setStartTime(shopProxyRefundDto.getStartTime());
    	totalShopRefundStatisticsVo.setEndTime(shopProxyRefundDto.getEndTime());
    	List<TaxStatisticsDetailVo> taxDetailLs = refundTaxService.totalShopStatistic(query);
    	totalShopRefundStatisticsVo.setTaxDetailLs(taxDetailLs);
    	return ResponseUtil.ok(totalShopRefundStatisticsVo);
    }

    /**
     * 细节
     * 店铺退款汇总统计
     *
     * @param id id
     * @return {@link Object}
     */
    public Object detail(Integer id) {
    	Validate.notNull(id);
    	RefundDetailVo detail = new RefundDetailVo();
    	LitemallRefund refund = refundService.findById(id);
    	BeanUtils.copyProperties(refund, detail);
    	detail.setOperationName(getUserName(refund.getAddUserId()));
    	detail.setUserName(getUserName(refund.getUserId()));
    	detail.setRefundShopName(getShopName(refund.getRefundShopId()));
    	
    	List<LitemallRefundGoods> refundGoodsLs = refundGoodsService.findByRefundId(id);
    	List<RefundGoodsVo> goodsLs = new ArrayList<>();
    	 if(!CollectionUtils.isEmpty(refundGoodsLs)) {
         	for (LitemallRefundGoods litemallRefundGoods : refundGoodsLs) {
         		RefundGoodsVo goodsVo = new RefundGoodsVo();
         		BeanUtils.copyProperties(litemallRefundGoods, goodsVo);
         		
         		Integer orderGoodsId = litemallRefundGoods.getOrderGoodsId();
         		LitemallOrderGoods litemallOrderGoods = orderGoodsService.findById(orderGoodsId);
         		goodsVo.setGoodsName(litemallOrderGoods.getGoodsName());
         		goodsVo.setGoodsSn(litemallOrderGoods.getGoodsSn());
         		goodsVo.setSellingPrice(litemallOrderGoods.getSellingPrice());
         		goodsVo.setGoodsPrice(litemallOrderGoods.getSellingPrice().multiply(new BigDecimal(litemallRefundGoods.getNumber())));
         		goodsVo.setDiscountPrice(litemallRefundGoods.getUnitPrice());
         		goodsVo.setDiscountGoodsPrice(litemallRefundGoods.getGoodsPrice());
         		
 				//查询规格辅料
 				String[] specifications = litemallOrderGoods.getSpecifications();
 				StringBuffer specAndAccessory = new StringBuffer(specifications[0]);
 				String accessory = getGoodsAccessoryStr(orderGoodsId);
 				if(!StringUtils.isEmpty(accessory)) {
 					specAndAccessory.append("/").append(accessory);
 				}
 				goodsVo.setSpecAndAccessory(specAndAccessory.toString());
 				
 				//查询订单商品的税费表
 				List<LitemallRefundTax> refundTaxs = refundTaxService.findByRefundIdAndRefundGoodsId(id, litemallRefundGoods.getId());
 				goodsVo.setTaxs(refundTaxs);
         		goodsLs.add(goodsVo);
 			}
        }
    	
    	detail.setGoodsLs(goodsLs);
    	return ResponseUtil.ok(detail);
    }

    /**
     * 获得商品配件str
     * 获取商品的辅料字符串
     *
     * @param orderGoodsId 订单商品id
     * @return {@link String}
     */
    private String getGoodsAccessoryStr(Integer orderGoodsId) {
    	StringBuffer sb = new StringBuffer();
    	List<LitemallOrderGoodsAccessory> accessoryList = litemallOrderGoodsAccessoryService.findByOrderGoodsId(orderGoodsId);
		if(!CollectionUtils.isEmpty(accessoryList)) {
			for (int i = 0; i < accessoryList.size(); i++) {
				LitemallOrderGoodsAccessory accessory = accessoryList.get(i);
				sb.append(accessory.getAccessoryName());
				if(accessory.getNumber() >= 0) {
					sb.append("+");
				}
				sb.append(accessory.getNumber());
				if(i<accessoryList.size()-1) {
					sb.append("、");
				}
			}
		}
		return sb.toString();
    }

    /**
     * 获得用户名
     *
     * @param userId 用户id
     * @return {@link String}
     */
    private String getUserName(Integer userId) {
    	if(null != userId) {
    		LitemallUser user = userService.findById(userId);
    		return user != null ? user.getUsername() : "";
    	}
    	return "";
    }

    /**
     * 店名字
     *
     * @param shopId 商店id
     * @return {@link String}
     */
    private String getShopName(Integer shopId) {
    	LitemallShop shop = shopService.findById(shopId);
    	return shop != null ? shop.getName() : "";
    }
}
